﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Collections.Generic;
using System;
using AutoMapper;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using LinqKit;
using Ccteg.Common;
using CCcteg.Common;
using Ccteg.DB;
using Cari.IBP.Platform.Sidecar;
using Cari.IBP.Platform.Utility;

namespace Cctegaq.Api.Controllers
{
    /// <summary>
    /// 安全风险业务
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SRBController : IbpControllerBase
    {
        private readonly AppAuthenticationSettings _appSettings;
        private readonly MySqlDbContext _dbContext;
        private readonly IMapper _mapper;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appSettings"></param>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        public SRBController(IOptions<AppAuthenticationSettings> appSettings, MySqlDbContext dbContext, IMapper mapper)
        {
            _appSettings = appSettings.Value;
            _dbContext = dbContext;
            _mapper = mapper;
        }



        /// <summary>
        /// 获取安全风险业务数据 4类
        /// </summary>
        /// <param name="companyno">二级单位编码</param>
        /// <param name="trade">行业</param>
        ///  <param name="category">业务类型</param>
        /// <param name="srbname">安全风险业务名称</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        [ResourceDeclare(Identity = "/SRB", Name = "安全风险业务", Operation = Constants.OPERATION_BROWSE)]
        public ResponseResultModel<List<V_srb_main_ViewModel>> GetList(string companyno, string trade, string category, string srbname, int pageindex = 1, int pagesize = 10)
        {
            var res = new ResponseResultModel<List<V_srb_main_ViewModel>>();
            string where = " where 1=1  and Deleted=0 ";
            if (!string.IsNullOrEmpty(companyno))
            {
                where += $"  and companyno='{companyno}' ";
            }
            if (!string.IsNullOrEmpty(trade))
            {
                where += $"  and trade='{trade}' ";
            }
            if (!string.IsNullOrEmpty(category))
            {
                where += $"  and category='{category}' ";
            }
            if (!string.IsNullOrEmpty(srbname))
            {
                where += $"  and   srbname like '%{srbname}%' ";
            }
            try
            {
                int offset = (pageindex - 1) * pagesize;
                using (_dbContext)
                {
                    var query = _dbContext.Database.FromSql<V_srb_main_ViewModel>($" select * from v_srb_main   {where} order by id desc limit {pagesize}  offset  {offset}");
                    var queryTotal = _dbContext.Database.SqlQuery($" select count(1) total from v_srb_main   {where} ");
                    res.SetData(query, int.Parse(queryTotal.Rows[0]["total"].ToString()));
                    return res;
                }
            }
            catch (Exception ex)
            {
                res.Data = new List<V_srb_main_ViewModel>();
                res.Message = ex.Message;
                return res;
            }
        }

        /// <summary>
        /// 安全风险业务(工程详情)
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<Srb_main_project_ViewModel> GetSrBprojectDetails([Required] int id)
        {
            var res = new ResponseResultModel<Srb_main_project_ViewModel>();

            try
            {
                using (_dbContext)
                {
                    var entity = _dbContext.Srb_Main_Project.FirstOrDefault(x => x.Id == id);
                    var model = _mapper.Map<srb_main_project, Srb_main_project_ViewModel>(entity);
                    res.TotalCount = entity == null ? 0 : 1;
                    res.Data = model;

                }
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Message = ex.Message;

            }
            return res;
        }

        /// <summary>
        /// 安全风险业务(托管煤矿详情)
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<srb_main_mine> GetSrbMainMineDetails([Required] int id)
        {
            var res = new ResponseResultModel<srb_main_mine>();

            try
            {
                using (_dbContext)
                {
                    var entity = _dbContext.Srb_Main_Mine.FirstOrDefault(x => x.Id == id);

                    res.TotalCount = entity == null ? 0 : 1;
                    res.Data = entity;

                }
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Message = ex.Message;

            }
            return res;
        }
        /// <summary>
        /// 安全风险业务(自有煤矿详情)
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<srb_main_mine_self> GetSrbMainMineSelfDetails([Required] int id)
        {
            var res = new ResponseResultModel<srb_main_mine_self>();

            try
            {
                using (_dbContext)
                {
                    var entity = _dbContext.Srb_Main_Mine_Self.FirstOrDefault(x => x.Id == id);

                    res.TotalCount = entity == null ? 0 : 1;
                    res.Data = entity;

                }
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Message = ex.Message;

            }
            return res;
        }

        /// <summary>
        /// 安全风险业务(加工基地详情)
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<srb_main_processingbase> GetSrbMainProcessingbaseDetails([Required] int id)
        {
            var res = new ResponseResultModel<srb_main_processingbase>();

            try
            {
                using (_dbContext)
                {
                    var entity = _dbContext.Srb_Main_Processingbase.FirstOrDefault(x => x.Id == id);

                    res.TotalCount = entity == null ? 0 : 1;
                    res.Data = entity;

                }
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Message = ex.Message;

            }
            return res;
        }

        /// <summary>
        /// 安全风险业务清单
        /// </summary>
        /// <param name="srbno">安全风险业务编号</param>
        /// <param name="companyno">二级单位编码</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<IEnumerable<Srb_main_risk_ViewModel>> GetSrbmainriskSearch([Required] string srbno, [Required] string companyno, int pageindex = 1, int pagesize = 10)
        {

            using (_dbContext)
            {
                var response = ResponseModelFactory<IEnumerable<Srb_main_risk_ViewModel>>.CreateResultInstance;
                var query = _dbContext.srb_main_risk.Where(x => x.SrbNo == srbno && x.CompanyNo == companyno);
                query = query.OrderByDescending(x => x.Id);
                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<srb_main_risk, Srb_main_risk_ViewModel>);
                response.SetData(data, totalCount);
                return response;

            }
        }

        /// <summary>
        /// 安全风险业务措施
        /// </summary>
        /// <param name="riskno">风险编号</param>
        /// <param name="companyno">二级单位编码</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<IEnumerable<Srb_main_risk_measure_ViewModel>> GetSrbMeasureSearch([Required] string riskno, [Required] string companyno, int pageindex = 1, int pagesize = 10)
        {

            using (_dbContext)
            {
                var response = ResponseModelFactory<IEnumerable<Srb_main_risk_measure_ViewModel>>.CreateResultInstance;
                var query = _dbContext.srb_main_risk_measure.Where(x => x.RiskNo == riskno && x.CompanyNo == companyno);
                query = query.OrderByDescending(x => x.Id);
                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<srb_main_risk_measure, Srb_main_risk_measure_ViewModel>);
                response.SetData(data, totalCount);
                return response;
            }
        }

    }
}